<?php
/**
 * Created by PhpStorm.
 * Author: sitenv@aliyun.com
 * CreateTime: 2021/07/23 22:01
 * Blog：www.myblogs.xyz
 */

namespace app\api\controller;


use app\common\model\Area;
use app\common\model\Balance;
use app\common\model\BillingSetting;
use app\common\model\MemberBalance;
use app\common\model\MemberFinance;
use app\common\model\Order;
use app\common\model\PlatformWallet;

class Payment extends Common
{
    public function into()
    {
        $this->require = ['payment_mode', 'type'];
        $this->selectable = ['money', 'number', 'ids', 'area_id', 'type_id'];
        $this->verifyParam();
        $this->verifyToken();
        // 获取车辆车辆信息
        $vehicle_model = new \app\common\model\Vehicle();
        $vehicle_data = $vehicle_model->getVehicleInfo($this->data['ids'], true);
        if (!$vehicle_data){
            $this->jsonError($vehicle_model->getError());
        }
        // 获取区域是否开启
        $area_model = new Area();
        $state = $area_model->getField($vehicle_data['area_id'], 'state');
        if (empty($state)){
            $this->jsonError('该车辆暂不提供服务，请耐心等待');
        }
        // 获取收费数据
        $billing_setting = new BillingSetting();
        $billing_data = $billing_setting->getBillingSetting($vehicle_data['type_id'], $vehicle_data['area_id']);
        $result['deposit'] = $billing_data->deposit;
        $result['charge_mode'] = $billing_data->charge_mode;
        $result['time_billing'] = $billing_data->time_billing;
        $money = floatval($this->data['money']) - floatval($result['deposit']);
        // 获取租用时间
        $end_time = 0;
        if (!empty($result['time_billing'])){
            if (is_array($result['time_billing'])){
                foreach ($result['time_billing'] as $key=>$val){
                    if (floatval($val['money']) == floatval($money)){
                        $use_time = $val['name'];
                        switch ($result['charge_mode']){
                            case 0:
                                $end_time = ($use_time*3600);
                                break;
                            case 1:
                                $end_time = ($use_time*86400);
                                break;
                            case 2:
                                $end_time = ($use_time*604800);
                                break;
                            case 3:
                                $end_time = ($use_time*2678400);
                                break;
                        }
                        if ($end_time > 0){
                            $end_time += NEW_TIME;
                        }
                    }
                }
            }
        }
        if (empty($end_time)){
            $this->jsonError('租车失败，请稍后再试');
        }
        // 订单支付
        $body = '订单支付';
        $type = 3;
        $total = 0;
        // 订单号
        $order_code = order_code();
        $this->data['type'] = 3;
        // 交易情况
        $type_id = $vehicle_data['type_id'];
        $vehicle_id = $vehicle_data['vehicle_id'];
        $area_id = $vehicle_data['area_id'];
        $admin_id = $vehicle_data['admin_id'];
        // 缓存数据KEY
        $lock_data = md5(http_build_query($this->data));
        // 创建订单信息
        $money = floatval($billing_data['deposit']);
        $vehicle_data['member_id'] = $this->memberId;
        $vehicle_data['deposit'] = $money;
        $vehicle_data['order_code'] = $order_code;
        $vehicle_data['trade_code'] = '';
        // 记录财务信息
        if (!empty($order_code)){
            $finance_data = [
                'remark'=>$body,
                'account'=>$this->memberData['account'],
                'mobile'=>$this->memberData['mobile'],
                'order_code'=>$order_code,
                'trade_code'=>'', // 第三方支付后交易凭证
                'total'=>$total,
                'money'=>$money,
                'member_id'=>$this->data['member_id'],
                'type_id'=>$type_id,
                'vehicle_id'=>$vehicle_id,
                'area_id'=>$area_id,
                'admin_id'=>$admin_id,
                'payment_mode'=>$this->data['payment_mode'],
                'type'=>$type,
                'ids'=>empty($this->data['ids']) ? 0 : $this->data['ids'],
                'create_time'=>NEW_TIME
            ];
            $member_finance = new MemberFinance();
            $finance_id = $member_finance->getField(['order_code'=>$order_code], 'finance_id');
            if (!empty($finance_id)){
                $finance_data['finance_id'] = $finance_id;
                $rows = $member_finance->operation($finance_data, false);
                if (empty($rows)){
                    $this->jsonError('支付失败，请稍后再试');
                }
            }else{
                $finance_id = $member_finance->insert($finance_data);
                if (empty($finance_id)){
                    $this->jsonError('支付失败，请稍后再试');
                }
            }
            // 开启事务处理
            $order_model = new Order();
            // 记录订单信息
            $rows = $this->unlock($vehicle_data, false);
            if (!$rows){
                cache($lock_data, null);
                $this->jsonError('支付失败，请稍后再试');
            }
        }
        // 微信小程序
        if ($this->data['payment_mode'] == 5){
            $wx_pay = new WxPay();
            // 订单参数
            $param = [
                'money'=>$money,
                'body'=>$body,
                'subject'=>$body,
                'order_code'=>$order_code,
                'openid'=>$this->memberData['openid'],
                'notify_url'=>$this->httpUrl . '/api.php/payment/wxCallBack'
            ];
            $rows = $wx_pay->wxPayNative($param);
            if (!$rows){
                cache($lock_data, null);
                $this->jsonError($wx_pay->getError());
            }
            $this->jsonResult($rows);
        }
        $this->jsonError('支付无效');
    }

    // 微信回调处理
    public function wxCallBack()
    {
        $data = file_get_contents('php://input');
        if (!empty($data)){
            $data = $this->FromXml($data);
        }
        if (!empty($data)) {
            // 判断是否支付成功
            if ($data['return_code'] == 'SUCCESS') {
                // out_trade_no 商家订单号 transaction_id 微信支付订单号
                $this->paySuccess($data['out_trade_no'], $data['transaction_id']);
            }
        }
    }

    protected function paySuccess($order_code = '', $trade_code = '')
    {
        if (empty($order_code)) return false;
        $member_finance = new MemberFinance();
        $finance_data = $member_finance->getFind(['order_code'=>$order_code]);
        if (!empty($finance_data)) {
            if ($finance_data['is_payment'] == 0){
                $balance_model = new Balance();
                $platform_wallet = new PlatformWallet();
                // 支付成功更新数据
                $up_data = ['trade_code'=>$trade_code,'is_payment'=>1];
                // type 1账户充值，2缴纳押金，3订单支付，4缴纳罚款，5购买优惠券
                if ($finance_data['type'] == 3){
                    // 增加用户累计骑行消费
                    $member_balance = new MemberBalance();
                    $member_balance->balanceInc($finance_data['member_id'], floatval($finance_data['total']), 'consume');
                    // 增加平台用户累计骑行消费
                    $platform_wallet->walletInc(floatval($finance_data['total']), 'consume');
                    // 支付方式：1余额，2微信，3支付宝，4银行卡，5微信小程序，6支付宝小程序
                    /*if ($finance_data['payment_mode'] == 1){
                        // 增加平台用户累计余额消费
                        $platform_wallet->walletInc(floatval($finance_data['money']), 'balance_consume');
                    }*/
                    if ($finance_data['payment_mode'] == 2 || $finance_data['payment_mode'] == 5){
                        // 增加平台用户累计微信消费
                        $platform_wallet->walletInc(floatval($finance_data['money']), 'we_chat_consume');
                    }
                    /*if ($finance_data['payment_mode'] == 3 || $finance_data['payment_mode'] == 6){
                        // 增加平台用户累计支付宝消费
                        $platform_wallet->walletInc(floatval($finance_data['money']), 'ali_pay_consume');
                    }
                    if ($finance_data['payment_mode'] == 4){
                        // 增加平台用户累计银行卡消费
                        $platform_wallet->walletInc(floatval($finance_data['money']), 'pay_card_consume');
                    }*/
                    // 记录订单信息
                    $order_model = new Order();
                    // 更新订单信息
                    $update_order = [
                        'payment_code'=>$trade_code,
                        'payment_time'=>NEW_TIME,
                        'start_time'=>NEW_TIME,
                    ];
                    $order_model->where(['order_code'=>$finance_data['order_code'],'member_id'=>$finance_data['member_id']])
                        ->update($update_order);
                }
                // 增加平台资金池
                $balance_model->balanceInc(floatval($finance_data['money']));
                // 订单已付款
                $member_finance->where('finance_id', $finance_data['finance_id'])->update($up_data);
                // 获取平台费率设置
                $member_finance->totalRate($finance_data);
            }else{
                if ($finance_data['type'] == 3){
                    $discount = floatval($finance_data['total']) - floatval($finance_data['money']);
                    $save_order = [
                        'discount'=>$discount,
                        'mc_id'=>$finance_data['mc_id'],
                        'payment_time'=>NEW_TIME,
                        'payment_mode'=>$finance_data['payment_mode'],
                        'status'=>4
                    ];
                    $order_model = new Order();
                    $order_model->where('order_id', $finance_data['ids'])->update($save_order);
                }
            }
            if ($finance_data['payment_mode'] == 2 || $finance_data['payment_mode'] == 5){
                header("Content-type: text/xml");
                echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                exit();
            }
            if ($finance_data['payment_mode'] == 3 || $finance_data['payment_mode'] == 6){
                echo 'success';
                exit();
            }
        }
        return true;
    }

    /**
     * 将xml转为array
     * @param $xml
     * @return mixed|void
     */
    public function FromXml($xml)
    {
        if(!$xml){
            $this->jsonReturn(0,'','XML解析错误！');
        }
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }

}